<template>
  <div class="treeSelect">
    <el-select :value="valueTitle" :clearable="clearable" @clear="clearHandle" :filterable="filter"
      :popper-append-to-body="false" ref="select" @visible-change="handleScroll" :filter-method="filterMethod"
      :placeholder="placeholder">
      <el-option :value="valueTitle">
        <el-tree id="tree-option" ref="selectTree" :accordion="accordion" :data="data" :props="props"
          :node-key="nodeKey" :default-expanded-keys="defaultExpandedKey" :filter-node-method="filterNode"
          @node-click="nodeClick" :check-strictly="checkStrictly">
          <div class="el-select-tree__item" slot-scope="{ data }" :class="treeItemClass(data)">
            {{ data[props.label] }}
          </div>
        </el-tree>
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'el-tree-select',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    /* 配置项 */
    props: {
      type: Object,
      default: () => {
        return {
          value: 'id', // ID字段名
          label: 'title', // 显示名称
          children: 'children' // 子级字段名
        }
      }
    },
    /* 选项列表数据(树形结构的对象数组) */
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    /* 初始值 */
    value: {
      type: String,
      default: () => {
        return ''
      }
    },
    /* 可清空选项 */
    clearable: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    /* 是否可以多选，比较麻烦，以后再做 */
    multiple: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    /* 是否可以选择父节点 */
    checkStrictly: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    /* 可收索选项 */
    filter: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    /* 自动收起 */
    accordion: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    placeholder: {
      type: String,
      default: () => {
        return '请选择'
      }
    }
  },
  computed: {
    nodeKey() {
      return this.props.value || 'id'
    }
  },
  data() {
    return {
      valueId: this.value, // 初始值
      valueTitle: '',
      defaultExpandedKey: []
    }
  },
  mounted() {
    this.initHandle()
  },
  methods: {
    filterMethod(node) {
      this.$refs.selectTree.filter(node)
    },
    valueChange(value, node) {
      this.$emit('getValue', value, node)
    },
    // 初始化值
    initHandle() {
      if (this.valueId) {
        this.valueTitle = this.$refs.selectTree.getNode(this.valueId).data[
          this.props.label
        ] // 初始化显示
        this.$refs.selectTree.setCurrentKey(this.valueId) // 设置默认选中
        this.defaultExpandedKey = [this.valueId] // 设置默认展开
      }
      this.handleScroll()
    },
    // 初始化滚动条
    handleScroll() {
      this.$nextTick(() => {
        let scrollWrap = document.querySelectorAll(
          '.treeSelect .el-scrollbar .el-select-dropdown__wrap .el-select-dropdown__item'
        )[0]
        scrollWrap.scrollTop = 0
      })
    },
    // 切换选项
    nodeClick(data, node, component) {
      const children = data[this.props.children]
      const value = data[this.props.value]
      if (children && children.length && !this.checkStrictly) {
        component.handleExpandIconClick()
      } else if (!this.multiple) {
        if (value !== this.value) {
          this.valueChange(value, data)
          this.valueTitle = data[this.props.label]
        }
        this.valueId = data[this.props.value]
        this.defaultExpandedKey = []
        this.$refs.select.blur()
      }
    },
    // 清除选中
    clearHandle() {
      this.valueTitle = ''
      this.valueId = null
      this.defaultExpandedKey = []
      this.clearSelected()
      this.$emit('getValue', null)
    },
    /* 清空选中样式 */
    clearSelected() {
      let allNode = document.querySelectorAll('#tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
    },
    filterNode(value, data) {
      if (!value) return true
      return data[this.props.label].indexOf(value) !== -1
    },
    /* 选中的样式 */
    treeItemClass(data) {
      return {
        'is-selected': this.multiple
          ? false
          : data[this.props.value] === this.valueId
      }
    }
  },
  watch: {
    value: {
      handler(val, oldval) {
        !val && this.clearHandle()
        this.valueId = this.value
        this.initHandle()
      },
      deep: true
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
:deep(.el-select) {
  width: 100%;

}

:deep(.el-select-dropdown) {
  max-height: 280px;
  margin-top: 10px;
  left: 0 !important;
  position: absolute !important;
  top: 40px !important;

}

:deep(.el-scrollbar) {
  height: 100%;
  overflow: hidden;

}

:deep(.el-scrollbar__wrap) {
  overflow: initial;
  margin: 0 !important;

}

:deep(.el-select-dropdown__item) {
  height: auto;
  max-height: 200px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;

  &.selected {
    font-weight: normal;
  }

  .is-selected {
    color: #409eff;
    font-weight: 700;
  }

}

:deep(.el-tree-node__label) {
  color: #606266;
  font-weight: normal;
}

:deep(.el-tree-node__children) {
  color: #606266;
  font-weight: normal;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 0 20px;
}

:deep(.el-select-dropdown__item) {
  height: auto;
}
</style>
